<template>
  <div>
    <!-- 2.1.2修改课程评价 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="item.courseName + ' 课程评价'"
      :visible="open"
      append-to-body
      width="900px"
      @close="cancel()"
    >
      <div class="evaluate_cards">
         <!-- 工作站评价 -->
         <el-card v-show="item.workstationId">
          <div slot="header" class="clearfix">
            <span>工作站评价</span>
          </div>
          <el-form
            ref="workstation_form"
            :model="form"
            :rules="item.workstationId ? rules : {}"
            label-width="80px"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="设备整齐" prop="equipmentStar">
                  <el-rate
                    v-model="form.equipmentStar"
                    :disable="type == 2"
                    show-score
                    :score-template="`${form.equipmentStar.toFixed(1)} 分`"
                  ></el-rate>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="场地整洁" prop="envStar">
                  <el-rate
                    v-model="form.envStar"
                    :disable="type == 2"
                    show-score
                    :score-template="`${form.envStar.toFixed(1)} 分`"
                  ></el-rate>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="管理得当" prop="managerStar">
                  <el-rate
                    v-model="form.managerStar"
                    :disable="type == 2"
                    show-score
                    :score-template="`${form.managerStar.toFixed(1)} 分`"
                  ></el-rate>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="评价" prop="commentToWorkstation">
              <el-input
                v-if="type == 1"
                v-model="form.commentToWorkstation"
                maxlength="500"
                show-word-limit
                :autosize="{ minRows: 3, maxRows: 5 }"
                type="textarea"
                placeholder="请输入"
              />
              <div v-else style="white-space: pre-wrap">
                {{ form.commentToWorkstation }}
              </div>
            </el-form-item>
          </el-form>
        </el-card>
        <!-- 课程评价 -->
        <el-card>
          <div slot="header" class="clearfix">
            <span>课程评价</span>
          </div>
          <el-form
            ref="course_form"
            :model="form"
            :rules="rules"
            label-width="80px"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="教学设计" prop="courseStar">
                  <el-rate
                    v-model="form.courseStar"
                    :disable="type == 2"
                    show-score
                    :score-template="`${form.courseStar.toFixed(1)} 分`"
                  ></el-rate>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="资源精准" prop="resourcesStar">
                  <el-rate
                    v-model="form.resourcesStar"
                    :disable="type == 2"
                    show-score
                    :score-template="`${form.resourcesStar.toFixed(1)} 分`"
                  ></el-rate>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="难度适中" prop="difficultyStar">
                  <el-rate
                    v-model="form.difficultyStar"
                    :disable="type == 2"
                    show-score
                    :score-template="`${form.difficultyStar.toFixed(1)} 分`"
                  ></el-rate>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="评价" prop="commentToCourse">
              <el-input
                v-if="type == 1"
                v-model="form.commentToCourse"
                maxlength="500"
                show-word-limit
                :autosize="{ minRows: 3, maxRows: 5 }"
                type="textarea"
                placeholder="请输入"
              />
              <div v-else style="white-space: pre-wrap">
                {{ form.commentToCourse }}
              </div>
            </el-form-item>
          </el-form>
        </el-card>
        <!-- 教师评价 -->
        <el-card v-for="(item, index) in evaluateTeacherEntities" :key="index">
          <div slot="header" class="clearfix">
            <span>教师评价</span>
            <el-button
              v-if="evaluateTeacherEntities.length > 1"
              icon="el-icon-delete"
              style="float: right; padding: 3px 0"
              type="text"
              @click="deleteTeacherEvaluate(item, index)"
            >
              删除
            </el-button>
          </div>
          <el-form
            :ref="`teacher_form${index}`"
            :model="item"
            :rules="rules"
            label-width="80px"
          >
            <el-form-item label="授课教师" prop="teacherId">
              <!-- 下拉框 -->
              <el-select
                v-model="item.teacherId"
                placeholder="请选择"
                clearable
                filterable
                @change="onTeacherChange(index)"
              >
                <el-option
                  :disabled="selectedTeachers.includes(teacher.teacherId)"
                  v-for="(teacher, teacherindex) in initTeachers"
                  :key="teacherindex"
                  :label="teacher.name"
                  :value="teacher.teacherId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-row>
              <el-col :span="8">
                <el-form-item label="能力水平" prop="abilityStar">
                  <el-rate
                    v-model="item.abilityStar"
                    :disable="type == 2"
                    show-score
                    :score-template="`${item.abilityStar.toFixed(1)} 分`"
                  ></el-rate>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="敬业精神" prop="dedicatedStar">
                  <el-rate
                    v-model="item.dedicatedStar"
                    :disable="type == 2"
                    show-score
                    :score-template="`${item.dedicatedStar.toFixed(1)} 分`"
                  ></el-rate>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="教学热情" prop="enthusiasmStar">
                  <el-rate
                    v-model="item.enthusiasmStar"
                    :disable="type == 2"
                    show-score
                    :score-template="`${item.enthusiasmStar.toFixed(1)} 分`"
                  ></el-rate>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="评价" prop="commentToTeacher">
              <el-input
                v-if="type == 1"
                v-model="item.commentToTeacher"
                maxlength="500"
                show-word-limit
                :autosize="{ minRows: 3, maxRows: 5 }"
                type="textarea"
                placeholder="请输入"
              />
              <div v-else style="white-space: pre-wrap">
                {{ item.commentToTeacher }}
              </div>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 添加教师评价 按钮-->
        <el-button
          style="width: 100%"
          type="primary"
          @click="addTeacherEvaluate"
          v-if="evaluateTeacherEntities.length < initTeachers.length"
          >添加教师评价</el-button
        >
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

  <script>
import uploadImages from "@/components/uploadImages.vue";
import { uploadsInCourse } from "@/api/upload";
import { evaluate } from "@/api/mine/mine";
import { getCourseTeacherList } from "@/api/teach/teach";
export default {
  components: { uploadImages },
  props: {
    type: [String, Number],
    open: Boolean,
    item: [String, Object],
  },
  data() {
    let checkEvaluate = (rule, value, callback) => {
      if (!value > 0) {
        return callback(new Error("评价不能为空"));
      } else {
        callback();
      }
    };
    return {
      evaluateTeacherEntities: [],
      initTeachers: [], //授课教师列表
      selectedTeachers: [], // 已选择的教师ID列表
      // 表单参数
      form: {
        abilityStar: 0, //能力
        commentToCourse: "",
        commentToTeacher: "",
        commentToWorkstation: "",
        courseId: "",
        dedicatedStar: 0, //敬业
        difficultyStar: 0, //困难
        enthusiasmStar: 0, //热情
        envStar: 0, //环境
        equipmentStar: 0, //设备
        managerStar: 0, //管理
        resourcesStar: 0, //资源
        stuId: "",
        courseStar: 0, //教师
        workstationId: "",
      },
      // 表单校验
      rules: {
        teacherId: [
          { required: true, message: "教师不能为空", trigger: "blur" },
        ],
        courseStar: [
          {
            required: true,
            trigger: "blur",
            message: "请对 教学设计 进行评分",
            validator: checkEvaluate,
          }, //写入验证器
        ],
        resourcesStar: [
          {
            required: true,
            message: "请对 资源精准 进行评分",
            trigger: "blur",
            validator: checkEvaluate,
          },
        ],
        difficultyStar: [
          {
            required: true,
            message: "请对 难度适中 进行评分",
            trigger: "blur",
            validator: checkEvaluate,
          },
        ],
        equipmentStar: [
          {
            required: true,
            message: "请对 设备整齐 进行评分",
            trigger: "blur",
            validator: checkEvaluate,
          },
        ],
        envStar: [
          {
            required: true,
            message: "请对 场地整洁 进行评分",
            trigger: "blur",
            validator: checkEvaluate,
          },
        ],
        managerStar: [
          {
            required: true,
            message: "请对 管理得当 进行评分",
            trigger: "blur",
            validator: checkEvaluate,
          },
        ],
        abilityStar: [
          {
            required: true,
            message: "请对 能力水平 进行评分",
            trigger: "blur",
            validator: checkEvaluate,
          },
        ],
        dedicatedStar: [
          {
            required: true,
            message: "请对 敬业精神 进行评分",
            trigger: "blur",
            validator: checkEvaluate,
          },
        ],
        enthusiasmStar: [
          {
            required: true,
            message: "请对 教学热情 进行评分",
            trigger: "blur",
            validator: checkEvaluate,
          },
        ],
      },
    };
  },
  watch: {
    async open(e) {
      if (e) {
        await this.getCourseTeacherList();
      }
    },
  },
  mounted() {},
  methods: {
    deleteTeacherEvaluate(item, index) {
      for (let i = 0; i < this.selectedTeachers.length; i++) {
        if (item.teacherId == this.selectedTeachers[i])
          this.selectedTeachers.splice(i, 1);
      }
      this.evaluateTeacherEntities.splice(index, 1);
    },
    addTeacherEvaluate() {
      // 如果新增教师 只剩下最后一位 则直接生成
      if (this.initTeachers.length - this.evaluateTeacherEntities.length == 1) {
        let array1 = this.initTeachers.map((item) => item.teacherId);
        let array2 = this.evaluateTeacherEntities.map((item) => item.teacherId);
        const difference = array1.filter((item) => !array2.includes(item));
        this.evaluateTeacherEntities.push({
          teacherId: difference[0],
          commentToTeacher: "",
          abilityStar: 0,
          dedicatedStar: 0,
          enthusiasmStar: 0,
        });
      } else {
        this.evaluateTeacherEntities.push({
          teacherId: "",
          commentToTeacher: "",
          abilityStar: 0,
          dedicatedStar: 0,
          enthusiasmStar: 0,
        });
      }
    },
    onTeacherChange(index) {
      // 更新已选择的教师ID列表
      this.selectedTeachers = this.evaluateTeacherEntities
        .map((item) => item.teacherId)
        .filter((id) => id !== null);
    },
    // 获取授课教师
    async getCourseTeacherList() {
      try {
        let params = {
          courseId: this.item.courseId,
        };
        let res = await getCourseTeacherList(params);
        const { code, data } = res;
        if (code === 200) {
          this.initTeachers = data;
          // 如果教师数量为1个则直接赋值
          if (this.initTeachers.length === 1) {
            this.evaluateTeacherEntities.push({
              teacherId: this.initTeachers[0].teacherId,
              commentToTeacher: "",
              abilityStar: 0,
              dedicatedStar: 0,
              enthusiasmStar: 0,
            });
          } else {
            this.evaluateTeacherEntities.push({
              teacherId: "",
              commentToTeacher: "",
              abilityStar: 0,
              dedicatedStar: 0,
              enthusiasmStar: 0,
            });
          }
        }
      } catch (e) {
        console.error(e);
      }
    },
    // 校验所有教师
    async checkTeacher() {
      let allValid = true;
      for (let i = 0; i < this.evaluateTeacherEntities.length; i++) {
        try {
          await this.$refs[`teacher_form${i}`][0].validate();
        } catch (error) {
          allValid = false;
        }
      }
      return allValid;
    },
    /** 提交按钮 */
    async submitForm() {
      let allValid = await this.checkTeacher();
      this.$refs["workstation_form"].validate((valid1) => {
        this.$refs["course_form"].validate(async (valid2) => {
          if (valid1 && valid2 && allValid) {
            let data = { ...this.form };
            data.workstationId = this.item.workstationId;
            data.courseId = this.item.courseId;
            data.stuId = this.$store.getters.studentId;
            data.courseStuId = this.item.courseStuId;
            this.evaluateTeacherEntities.map((item) => {
              item.courseStuId = this.item.courseStuId;
            });
            data.evaluateTeacherEntities = this.evaluateTeacherEntities;
            evaluate(data).then((res) => {
              this.$modal.msgSuccess("评价成功");
              this.$emit("update:open", false);
              this.$emit("refresh");
            });
          }
        });
      });
    },
    // 文件上传
    async upload(files, type) {
      let formData = new FormData();
      Array.from(files).forEach((file) => {
        formData.append("files", file);
      });
      let res = await uploadsInCourse(formData);
    },
    // 表单重置
    reset() {
      this.resetForm("workstation_form");
      this.resetForm("course_form");
      this.resetForm("teacher_form");
      this.evaluateTeacherEntities = [];
      this.selectedTeachers = [];
      this.form = {
        abilityStar: 0, //能力
        commentToCourse: "",
        commentToTeacher: "",
        commentToWorkstation: "",
        courseId: 0,
        courseStar: 0,
        dedicatedStar: 0, //敬业
        difficultyStar: 0, //困难
        enthusiasmStar: 0, //热情
        envStar: 0, //环境
        equipmentStar: 0, //设备
        managerStar: 0, //管理
        resourcesStar: 0, //资源
        stuId: 0,
        workstationId: 0,
      };
    },
    cancel() {
      this.$emit("update:open", false);
      this.reset();
    },
  },
};
</script>
<style scoped lang="scss">
.evaluate_cards {
  height: calc(100vh - 260px);
  overflow-y: auto;
  ::v-deep .el-card {
    margin-bottom: 10px !important;
  }
  ::v-deep .el-rate {
    margin-top: 9px;
  }
  ::v-deep .el-card__header {
    font-size: 16px;
    font-weight: 800;
  }
  .uploadPicTip {
    margin-top: 10px;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC, sans-serif;
    font-weight: 400;
    color: #999999;
    line-height: 1;
  }
}
</style>
